<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--用户数据-->
      <el-col :span="mainwidth" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">

        </el-form>

        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px" style="margin-bottom: 10px">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-input
                v-model="queryParams.value"
                placeholder="查询值"
                clearable
                size="small"
                style="width: 350px"
                @keyup.enter.native="handleQuery"
              >
                <el-select
                  v-model="queryParams.type"
                  placeholder="查询条件"
                  clearable
                  slot="prepend"
                  style="width: 110px"
                >
                  <el-option
                    v-for="dict in typeOptionsCcUrl"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  />
                </el-select>
              </el-input>
            </el-col>
            <el-col :span="1.5">
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-col>

            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"

              >新增
              </el-button>
            </el-col>


            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>
        </el-form>

        <el-table v-loading="loading" :data="cardList" @selection-change="handleSelectionChange">
          <el-table-column label="序号" align="center" prop="id" v-if="columns[0].visible"/>
          <el-table-column label="姓名" align="center" prop="name" v-if="columns[1].visible"/>
          <el-table-column label="公司所属" align="center" prop="dept_id" v-if="columns[2].visible">
            <template slot-scope="scope" >
              {{tools.getDeptNamekeyValue(DeptOptions,scope.row.dept_id)}}
            </template>
          </el-table-column>
          <el-table-column label="头街" align="center" prop="head_street" v-if="columns[3].visible"/>
          <el-table-column label="电话" align="center" prop="phone" v-if="columns[4].visible"/>
          <el-table-column label="邮箱" align="center" prop="mailbox" v-if="columns[5].visible"/>
          <el-table-column label="电话通知" align="center" v-if="columns[6].visible">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.phonenotice"
                active-value="1"
                inactive-value="0"
                @change="PhonenoticeChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="短信通知" align="center" v-if="columns[8].visible">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.message_notice"
                active-value="1"
                inactive-value="0"
                @change="MessageNoticeChange(scope.row.message_notice)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="公众号" align="center" v-if="columns[9].visible">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.official_notice"
                active-value="1"
                inactive-value="0"
                @change="OfficialNoticeChange(scope.row.official_notice)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="绑定状态" align="center" prop="state" v-if="columns[9].visible"/>

          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >修改
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              >删除
              </el-button>
            </template>
          </el-table-column>

        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 新增联系人 -->
    <el-dialog :title="title" :visible.sync="automation" width="50%" append-to-body @close="automationClose">

      <el-row :gutter="20">
        <el-col :span="8" v-show="option_show" style="width: 400px">
          <div class="head-container">
            <el-input
              v-model="treeName"
              placeholder="请输入公司名称"
              clearable
              size="small"
              prefix-icon="el-icon-search"
              style="margin-bottom: 20px"
            />
          </div>
          <div class="head-container">
            <el-checkbox v-model="deptExpand" @change="handleCheckedTreeExpand($event, 'dept')">展开/折叠</el-checkbox>
            <el-checkbox v-model="deptNodeAll" @change="handleCheckedTreeNodeAll($event, 'dept')">全选/全不选</el-checkbox>
            <el-checkbox v-model="deptCheckStrictly" @change="handleCheckedTreeConnect($event, 'dept')">父子联动
            </el-checkbox>


            <el-tree :data="deptOptions" :check-on-click-node="false" ref="dept" :filter-node-method="filterNode"
                     show-checkbox :check-strictly="true" default-expand-all node-key="id"
                     :props="defaultProps" @check-change="treeNodeClick" empty-text="暂无数据">
            </el-tree>
          </div>
        </el-col>


        <el-col :span="8">
          <el-form :model="forContacts" :rules="rules" label-width="80px">

            <el-form-item label="通知方式" prop="blue" label-width="100px" style="margin-bottom:8px;" v-if="notice">
              <div style="width: 200px">
                <el-checkbox v-model="forContacts.phonenotice" :true-label="1" :false-label="0" style="color: blue">电话
                </el-checkbox>
                <el-checkbox v-model="forContacts.message_notice" :true-label="1" :false-label="0" style="color: blue">
                  短信
                </el-checkbox>
              </div>
            </el-form-item>

            <el-form-item label="姓名" prop="name" label-width="100px">
              <el-input v-model="forContacts.name" placeholder="请输入姓名" style="width: 220px"/>
            </el-form-item>
            <el-form-item label="接警号码" prop="phone" label-width="100px">
              <el-input v-model="forContacts.phone" placeholder="请输入手机号" style="width: 220px"
                        oninput="value=value.replace(/[^\d]/g,'')" maxlength="11"
              />
            </el-form-item>

            <el-form-item label-width="100px" style="margin-bottom:13px;margin-top:50px;">
              <div style="width: 200px">
                <el-button type="primary" plain size="mini" @click="Operator">公司所属</el-button>
                <el-button type="primary" plain size="mini" @click="noticeIf">通知方式</el-button>
              </div>
            </el-form-item>

            <el-form-item label="头街" prop="head_street" label-width="100px">
              <el-input v-model="forContacts.head_street" placeholder="请输入手机号" style="width: 220px"/>
            </el-form-item>
            <el-form-item label="邮箱" prop="mailbox" label-width="100px">
              <el-input v-model="forContacts.mailbox" placeholder="请输入手机号" style="width: 220px"/>
            </el-form-item>
          </el-form>
          <el-button type="primary" @click="submitAdd">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </el-col>
      </el-row>

    </el-dialog>

    <!-- 修改联系人 -->
    <el-dialog title="修改联系人" :visible.sync="updcontacts" width="30%" append-to-body>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form :model="form" label-width="80px">
            <el-form-item label="所属企业" prop="prop" label-width="100px">
              <el-input v-model="form.dept_id" :disabled="true" style="width: 220px"/>
            </el-form-item>
            <el-form-item label="姓名" prop="prop" label-width="100px">
              <el-input v-model="form.name" placeholder="请输入姓名" style="width: 220px"/>
            </el-form-item>
            <el-form-item label="电话" prop="prop" label-width="100px">
              <el-input v-model="form.phone" placeholder="请输入电话号" style="width: 220px"/>
            </el-form-item>
            <el-form-item label="头街" prop="head_street" label-width="100px">
              <el-input v-model="form.head_street" placeholder="请输入头街" style="width: 220px"/>
            </el-form-item>
            <el-form-item label="邮箱" prop="mailbox" label-width="100px">
              <el-input v-model="form.mailbox" placeholder="请输入邮箱" style="width: 220px"/>
            </el-form-item>
          </el-form>
          <el-button type="primary" style="margin-left: 330px" @click="preservation">保 存</el-button>
        </el-col>
      </el-row>
    </el-dialog>


  </div>
</template>

<script>
import {listLinkman, AddLinkman, PhoneLinkman, deleteKman, UpdLinkman} from "@/api/yunze/install/linkman";
import tools from "@/utils/yunze/tools";
import {findDeptUser} from "@/api/yunze/flowcard/card/card";
import {treeselect} from "@/api/system/dept";

export default {
  name: "index",
  data() {
    return {

      tools: tools,
      //条件查询
      typeOptionsCcUrl: [],
      cardList: [],//表格数组
      automation: false,//控制新增
      updcontacts: false,// 控制修改
      mainwidth: 24,//宽度
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: false,
      notice: true,//通知
      // 总条数
      total: 0,
      // 是否显示弹出层
      open: false,
      title: '',//新增表格
      treeName: undefined,//模糊查询公司

      //公司所属
      deptCheckStrictly: true,
      deptExpand: true,
      deptNodeAll: false,
      defaultProps: {
        children: "children",
        label: "label"
      },
      DeptOptions: [],//公司所属
      // 部门树选项
      deptOptions: undefined,
      selectList: [],
      formDivide: {
        dept_id: '',
        user_id: '',
      },
      //---------

      // 表单参数
      forContacts: {
        name: null,
        phone: null,
        head_street: null,
        mailbox: null,
        phonenotice: 1,
        message_notice: 1,
        dept_id: null,
      },
      //修改参数
      form: {
        name: null,
        phone: null,
        head_street: null,
        mailbox: null,
        dept_id: null,
      },
      //执行修改’
      formElse :{},
      option_show: false, //公司所属查询
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 列信息
      columns: [
        {key: 1, label: `序号`, visible: true},
        {key: 2, label: `姓名`, visible: true},
        {key: 3, label: `所属单位`, visible: true},
        {key: 4, label: `头街`, visible: true},
        {key: 5, label: `电话`, visible: true},
        {key: 6, label: `邮箱`, visible: true},
        {key: 7, label: `电话通知`, visible: true},
        {key: 8, label: `短信通知`, visible: true},
        {key: 9, label: `公众号`, visible: true},
        {key: 10, label: `绑定状态`, visible: true},
      ],
      // 表单校验
      rules: {
        name: [
          {required: true, message: "请输入姓名", trigger: "blur"}
        ],
        phone: [
          {
            required: true, message: "请您确保填写的接警号码真实有效，填入未经授权使用的号码带来的法律责任需自行承担\n" +
              "请输入手机号码或（区号+座机号码）", trigger: "blur"
          }
        ],
      }
    };
  },
  watch: {
    // 根据名称筛选企业树
    treeName(val) {
      this.$refs.dept.filter(val);
    },
  },

  created() {


    //加载 企业名称
    if (window['DeptOptions'] != undefined && window['DeptOptions'] != null && window['DeptOptions'] != '') {
      this.DeptOptions = window['DeptOptions'];
    } else {
      this.getDeptName().then(response => {
        let jsonobj = JSON.parse(tools.Decrypt(response));
        window['DeptOptions'] = jsonobj.Data;
        this.DeptOptions = window['DeptOptions'];
      });
    }
    this.getTreeselect();
    this.getList();

  },
  methods: {

    /**新增按钮*/
    handleAdd() {
      this.automation = true;//显示
      this.title = "新增联系人";
    },

    //关闭 自动化修改 清除 dept 选中
    automationClose() {
      this.$refs.dept.setCheckedKeys([]);
    },

    /**公司所属*/
    Operator() {
      this.option_show = !this.option_show;
      this.mainwidth = this.option_show ? 20 : 24;
    },
    /**通知方式*/
    noticeIf() {
      this.notice = !this.notice;
    },

    // 把树结构数据 插入数据库
    SetTree() {
      if (this.$refs.dept.getCheckedKeys().length > 0) { //判断 >0 执行 ---  这个 dept 是你在这个 el-tree 定义的 ref
        let arr = this.$refs.dept.getCheckedKeys(); //选中树结构 获取到数据
        // console.log(arr)
        let Str = "";
        for (let i = 0; i < arr.length; i++) {
          Str += arr[i] + ","; //把数据用逗号隔开  如：123,456,789,111,
          // console.log(Str)
        }
        Str = Str.substring(0, Str.length - 1); //把最后的逗号切割掉 如：123,456,789,111
        // console.log(Str)
        this.forContacts.dept_id = Str;
      }
    },

    /**电话通知*/
    PhonenoticeChange(row) {
      console.log(row)


    },
    /**短信通知*/
    MessageNoticeChange(row) {
      console.log(row)
    },
    /**公众号通知*/
    OfficialNoticeChange(row) {
      console.log(row)
    },

    /**修改*/
    handleUpdate(row) {
      console.log(row)
      // console.log(this.formElse.phone = row.phone)
      this.form.dept_id = Number(row.dept_id);
      this.form.dept_id = ""+ row.dept_id;
      this.formElse.phone = row.phone;//传固定参数

      this.form = row;
      this.updcontacts = true;
    },
    /**修改保存按钮*/
    preservation() {
      let _this = this;
      if (tools.VerificationsText(_this, _this.form.name, "姓名不能为空！") == true &&
        tools.VerificationsText(_this, _this.form.phone, "请您确保填写的接警号码真实有效，" +
          "填入未经授权使用的号码带来的法律责任需自行承担请输入手机号码或（区号+座机号码）") == true
      ) {
        // console.log(this.formElse.phone)
        if (this.formElse.phone === this.form.phone){
          let Pwd_Str = tools.encrypt(JSON.stringify(this.form));
          UpdLinkman(Pwd_Str).then(response => {
            let jsonobj = JSON.parse(tools.Decrypt(response));
            //console.log(jsonobj);
            if (jsonobj.code == 200) {
              this.msgSuccess(jsonobj.msg);
              this.updcontacts = false;
              this.handleQuery();
            } else {
              this.msgError("获取数据异常，请联系管理员！");
            }
          });
        }else {
          let Pwd_Str = tools.encrypt(JSON.stringify(this.form));
          PhoneLinkman(Pwd_Str).then(response => {
            let jsonobj = JSON.parse(tools.Decrypt(response));
            if (jsonobj.code != 200) {

              let Pwd_Str = tools.encrypt(JSON.stringify(this.form));
              UpdLinkman(Pwd_Str).then(response => {
                let jsonobj = JSON.parse(tools.Decrypt(response));
                //console.log(jsonobj);
                if (jsonobj.code == 200) {
                  this.msgSuccess(jsonobj.msg);
                  this.updcontacts = false;
                  this.handleQuery();
                } else {
                  this.msgError("获取数据异常，请联系管理员！");
                }
              });
            } else {
              this.msgError("手机号码已存在！");
            }
          });
        }

      }
    },

    /**删除*/
    handleDelete(row) {
      let map = {};
      map.id = row.id;
      let Pwd_Str = tools.encrypt(JSON.stringify(map));
      tools.openAsk(this, 'warning', "删除不可恢复，还要继续吗?", this.deleteID, Pwd_Str);
    },
    deleteID(Pwd_Str) {
      deleteKman(Pwd_Str).then(response => {
        let jsonobj = JSON.parse(tools.Decrypt(response));
        // console.log(jsonobj);
        if (jsonobj.code == 200) {
          this.getList();
          this.msgSuccess(jsonobj.msg);
        } else {
          let msg = jsonobj.Data != null && jsonobj.Data != '' ? jsonobj.Data : jsonobj.msg;
          this.msgError(msg);
        }
      })
    },


    /**新增确定按钮*/
    submitAdd() {
      this.SetTree();
      let _this = this;
      if (tools.VerificationsText(_this, _this.forContacts.name, "姓名不能为空！") == true &&
        tools.VerificationsText(_this, _this.forContacts.phone, "请您确保填写的接警号码真实有效，" +
          "填入未经授权使用的号码带来的法律责任需自行承担请输入手机号码或（区号+座机号码）") == true &&
        tools.VerificationsText(_this, _this.forContacts.dept_id, "公司所属不能为空！") == true) {

        let Pwd_Str = tools.encrypt(JSON.stringify(this.forContacts));
        PhoneLinkman(Pwd_Str).then(response => {
          let jsonobj = JSON.parse(tools.Decrypt(response));
          if (jsonobj.code != 200) {

            let Pwd_Str = tools.encrypt(JSON.stringify(this.forContacts));
            AddLinkman(Pwd_Str).then(response => {
              let jsonobj = JSON.parse(tools.Decrypt(response));
              //console.log(jsonobj);
              if (jsonobj.code == 200) {
                this.msgSuccess(jsonobj.msg);
                this.automation = false;
                this.handleQuery();
              } else {
                this.msgError("获取数据异常，请联系管理员！");
              }
            });

          } else {
            this.msgError("手机号码已存在！");
          }
        });
      }
    },

    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == 'dept') {
        let treeList = this.deptOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == 'dept') {
        //console.log(value);
        this.$refs.dept.setCheckedNodes(value ? this.deptOptions : []);
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == 'menu') {
        this.menuCheckStrictly = value ? true : false;
      } else if (type == 'dept') {
        this.$refs.dept.setCheckedNodes(false ? this.deptOptions : []);
        this.deptCheckStrictly = value ? true : false;

      }
    },


    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },

    treeNodeClick(data, checked) {
      //console.log(data)
      this.userArr = [];
      const node = this.$refs.dept.getNode(data);
      //console.log(node)
      const str = [];
      /*function filterName (node) {
        if (node) {
          if (node.parent) {
            str.push(node.data.label);
            filterName(node.parent);
          }
        }
      }*/
      // 获取当前选择的id在数组中的索引
      const indexs = this.selectList.indexOf(data.id);
      // 如果不存在数组中，并且数组中已经有一个id并且checked为true的时候，代表不能再次选择。
      if (indexs < 0 && this.selectList.length === 1 && checked) {
        this.msgError("单选操作请勿多选！");
        // 设置已选择的节点为false 很重要
        this.$refs.dept.setChecked(data, false);
      } else if (this.selectList.length === 0 && checked) {
        // 发现数组为空 并且是已选择
        // 防止数组有值，首先清空，再push
        this.selectList = [];
        this.formDivide.dept_id = '';
        this.selectList.push(data.id);
        //filterName(node);

        //this.formDivide.dept_id = str.reverse().join('/');
        //this.formDivide.dept_id = str[0];
        this.formDivide.dept_id = data.id;
        this.formDivide.dept_name = data.label;
        //获取企业下用户
        this.userArr = [];
        this.formDivide.user_id = null;
        let map = {};
        map.dept_id = this.formDivide.dept_id;
        let Pwd_Str = tools.encrypt(JSON.stringify(map));
        findDeptUser(Pwd_Str).then(response => {
            let jsonobj = JSON.parse(tools.Decrypt(response));
            //console.log(jsonobj);
            if (jsonobj.code == 200) {
              this.userArr = jsonobj.Data;
            } else {
              this.msgError(jsonobj.msg);
            }
            this.loading = false;
          }
        );

        //console.log(this.formDivide.dept_id);
      } else if (indexs >= 0 && this.selectList.length === 1 && !checked) {
        // 再次直接进行赋值为空操作
        this.selectList = [];
        this.formDivide.dept_id = '';
        this.forContacts.dept_id = '';
      }
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.jobId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },

    /*获取查询参数*/
    getParams() {

      if (this.$refs.dept != undefined & this.$refs.dept != null & this.$refs.dept != 'undefined') {
        //console.log(this.$refs.dept.getCheckedKeys());
        if (this.$refs.dept.getCheckedKeys().length > 0) {
          this.queryParams.agent_id = this.$refs.dept.getCheckedKeys();
        }
      }
      if (tools.Is_null(this.queryParams.timetype) && this.selTime != null) {
        //console.log(this.selTime);
        this.queryParams.staTime = this.selTime[0];
        this.queryParams.endTime = this.selTime[1];
      }


    },


    /** 查询执行日志列表 */
    getList() {
      this.loading = true;
      this.getParams();
      this.queryParams.page = 1;
      //console.log(this.queryParams);
      let Pwd_Str = tools.encrypt(JSON.stringify(this.queryParams));
      //console.log(Pwd_Str);
      listLinkman(Pwd_Str).then(response => {
          let jsonobj = JSON.parse(tools.Decrypt(response));
          // console.log(jsonobj);
          if (jsonobj.code == 200) {
            this.cardList = jsonobj.Data.Data;
            this.total = jsonobj.Data.Pu.rowCount;
          } else {
            this.msgError("获取数据异常，请联系管理员！");
          }
          this.loading = false;
        }
      );
    },


    // 取消按钮
    cancel() {
      this.automation = false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {};
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;
      this.selTime = null;
      this.handleQuery();
    },


  }
};
</script>

<style scoped>


</style>

